//
//  Persistence.m
//  ET
//
//  Created by centling on 13-12-25.
//  Copyright (c) 2013年 Zhaoyu Li. All rights reserved.
//

#import "QTProductPersistence.h"


@implementation QTProductPersistence

@synthesize managedObjectContext;
@synthesize managedObjectModel;
@synthesize persistentStoreCoordinator;


//确定sqlite文件存储路径
-(NSURL *)storeURL{
    //得到数据库的路径
    NSArray *documnetDir=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
    NSString *docDir=[documnetDir objectAtIndex:0];
    NSLog(@"*** If you compile this Project first time please Create folder:%@  ***",docDir);
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:docDir isDirectory:&isDir];
    if ( !(isDir == YES && existed == YES) )
    {
        [fileManager createDirectoryAtPath:docDir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *path=[docDir stringByAppendingPathComponent:@"CoreData.sqlite"];
    NSURL *storeURL=[NSURL fileURLWithPath:path];
    return storeURL;
}


- (NSManagedObjectModel *)managedObjectModel {
    
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    return managedObjectModel;
}


//managedObjectModel的初始化赋值函数
-(NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }
    
    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:self.managedObjectModel];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self storeURL] options:nil error:&error]) {
        NSLog(@"Error: %@,%@",error,[error userInfo]);
        [NSException raise:@"open failed" format:@"Reason:%@",[error localizedDescription]];
    }
    
    return persistentStoreCoordinator;
}

//managedObjectContext的初始化赋值函数
-(NSManagedObjectContext *)managedObjectContext
{
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator =self.persistentStoreCoordinator;
    
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc]init];
        [managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    
    return managedObjectContext;
}

-(BOOL)saveHistory:(Product *)product {
    // 利用上下文对象，将数据同步到持久化存储库
    
    //首先查询coredata中记录
    NSArray *array=[self queryHistory:product.puid];
    NSError *error = nil;
    
    //如果coredata中没有这条记录，则添加
    if ([array count]==0) {
        NSManagedObject *productManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Product" inManagedObjectContext:self.managedObjectContext];
        // 设置Person的简单属性
        [productManagedObject setValue:product.puid forKey:@"puid"];
        [productManagedObject setValue:product.productName forKey:@"productName"];
        [productManagedObject setValue:product.filePath forKey:@"filePath"];
        [productManagedObject setValue:product.date forKey:@"date"];
        BOOL success = [self.managedObjectContext save:&error];
        if (!success) {
            [NSException raise:@"访问数据库错误" format:@"%@", [error localizedDescription]];
            return NO;
        }
        return YES;
    }
    //如果coredata中有这已经存在记录，则修改时间
    else {
        Product *product=[array objectAtIndex:0];
        product.date=[[NSDate alloc] init];
        BOOL success = [self.managedObjectContext save:&error];
        if (!success) {
            [NSException raise:@"访问数据库错误" format:@"%@", [error localizedDescription]];
            return NO;
        }
        return YES;
    };
    
}

-(NSArray *)getHistory{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entityDescription=[NSEntityDescription entityForName:@"Product" inManagedObjectContext:self.managedObjectContext];
    request.entity = entityDescription;
    // 设置排序（按照date降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
        return nil;
    }
    NSMutableArray *productArray=[[NSMutableArray alloc] init];
    //-----------------------Persistence---------------------
    QTProductPersistence *persistence=[[QTProductPersistence alloc] init];
    for (int i=0; i<[objs count]; i++) {
        Product *product=[[Product alloc] init];
        product.puid=((Product *)[objs objectAtIndex:i]).puid;
        product.productName=((Product *)[objs objectAtIndex:i]).productName;
        product.date=((Product *)[objs objectAtIndex:i]).date;
        product.filePath=((Product *)[objs objectAtIndex:i]).filePath;
        [productArray addObject:product];
    }
    return productArray;
}


//-(NSArray *)updateHistory:(Product *)product{
//    [productManagedObject setValue:product.date forKey:@"date"];
//    BOOL success = [self.managedObjectContext save:&error];
//}

-(NSArray *)queryHistory:(NSString *)puid{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entityDescription=[NSEntityDescription entityForName:@"Product" inManagedObjectContext:self.managedObjectContext];
    request.entity = entityDescription;
    NSPredicate *predicate=[NSPredicate predicateWithFormat:@"puid=%@",puid];
    [request setPredicate:predicate];
    [request setFetchLimit:1];//限定数量
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
        return nil;
    }
    NSLog(@"%@",objs);
    return objs;
}

-(BOOL)deleteHistory{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Product" inManagedObjectContext:self.managedObjectContext];
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (!error && objs && [objs count])
    {
        for (NSManagedObject *obj in objs)
        {
            [self.managedObjectContext deleteObject:obj];
        }
        if (![self.managedObjectContext save:&error])
        {
            NSLog(@"error:%@",error);
            return NO;
        }
    }
    return YES;
}

@end
